from bank_manage_system.database.db_connector import DatabaseConnector
import logging


class DepositManager:
    def __init__(self, db: DatabaseConnector):
        self.db = db
        self.logger = logging.getLogger(__name__)

    def add_deposit(self, card_id: str, amount: float) -> dict:

        try:
            # 检查银行卡是否存在
            card_query = "SELECT 1 FROM cardinfo WHERE cardID = %s"
            card_exists = self.db.execute_query(card_query, (card_id,))
            if not card_exists:
                return {"success": False, "message": "银行卡不存在"}


            query = """
            INSERT INTO tradeinfo 
            (cardID, tradeType, tradeMoney)
            VALUES (%s, '存入', %s)
            """
            self.db.execute_query(query, (card_id, amount))
            self.logger.info(f"成功添加存款: 卡号 {card_id}, 金额 {amount}")

            return {"success": True, "message": "存款成功"}
        except Exception as e:
            self.logger.error(f"存款失败: {str(e)}", exc_info=True)
            return {"success": False, "message": f"存款失败: {str(e)}"}

    def reverse_deposit(self, trade_id: int) -> dict:
        """
        冲正存款交易

        """
        try:
            # 1. 获取原存款交易信息
            query = """
            SELECT cardID, tradeMoney 
            FROM tradeinfo 
            WHERE tradeID = %s AND tradeType = '存入'
            """
            original = self.db.execute_query(query, (trade_id,))
            if not original:
                return {"success": False, "message": "存款交易记录不存在"}

            card_id = original[0]['cardID']
            amount = original[0]['tradeMoney']

            # 2. 插入冲正交易记录（类型为'取款'）
            reverse_query = """
            INSERT INTO tradeinfo 
            (cardID, tradeType, tradeMoney, remark)
            VALUES (%s, '支取', %s, '冲正存款ID: %s')
            """
            self.db.execute_query(reverse_query, (card_id, amount, trade_id))

            self.logger.info(f"成功冲正存款交易: ID {trade_id}, 金额 {amount}")
            return {"success": True, "message": "存款冲正成功"}
        except Exception as e:
            self.logger.error(f"冲正失败: {str(e)}", exc_info=True)
            return {"success": False, "message": f"冲正失败: {str(e)}"}

    def get_deposit_history(self, card_id: str = None) -> dict:
        """
        查询存款记录
        """
        try:
            query = """
            SELECT 
                tradeID AS 交易ID,
                cardID AS 卡号,
                tradeDate AS 交易时间,
                tradeMoney AS 交易金额,
                remark AS 备注
            FROM tradeinfo
            WHERE tradeType = '存入'
            """

            params = ()
            if card_id:
                query += " AND cardID = %s"
                params = (card_id,)

            results = self.db.execute_query(query, params)
            return {"success": True, "data": results}
        except Exception as e:
            self.logger.error(f"查询存款记录失败: {str(e)}", exc_info=True)
            return {"success": False, "message": f"查询失败: {str(e)}"}

    def get_card_balance(self, card_id: str) -> float:
        """
        获取银行卡余额
        """
        try:
            query = "SELECT balance FROM cardinfo WHERE cardID = %s"
            result = self.db.execute_query(query, (card_id,))
            return float(result[0]['balance']) if result else 0.0
        except Exception as e:
            self.logger.error(f"查询余额失败: {str(e)}")
            return 0.0

    def debug_cardinfo(self, card_id: str):
        """
        调试方法：打印cardinfo表结构
        """
        try:
            # 获取表结构
            desc_query = "DESCRIBE cardinfo"
            structure = self.db.execute_query(desc_query)
            print("cardinfo表结构:")
            for col in structure:
                print(f"{col['Field']}: {col['Type']}")

            # 获取具体银行卡信息
            data_query = "SELECT * FROM cardinfo WHERE cardID = %s"
            data = self.db.execute_query(data_query, (card_id,))
            print(f"\n卡号 {card_id} 的数据:")
            if data and data[0]:
                for key, value in data[0].items():
                    print(f"{key}: {value}")
            else:
                print("银行卡不存在")
        except Exception as e:
            print(f"调试失败: {str(e)}")

